<template>
  <div class="channel-edit">
    <!-- 我的频道区域 -->
    <van-cell :border="false">
      <div slot="title" class="title-text">我的频道</div>
      <van-button
        class="edit-btn"
        type="info"
        plain
        size="mini"
        @click="isEdit = !isEdit"
        >{{ isEdit ? '完成' : '编辑' }}</van-button
      >
    </van-cell>
    <van-grid :gutter="10" class="my-grid">
      <van-grid-item
        class="grid-item"
        v-for="(channel, index) in myChannels"
        :key="index"
        @click="removeMychannel(channel, index)"
        ><van-icon
          v-show="isEdit && !fiexdChannels.includes(channel.id)"
          slot="icon"
          name="clear"
        ></van-icon>
        <!-- v-bind:class 语法
        一个对象，对象中的 key 表示要作用的 css 类名
        对象中的 value 要计算出布尔值 true：表示作用改类名 false：表示不作用改类名
       -->
        <span slot="text" :class="{ active: active === index }" class="text">{{
          channel.name
        }}</span></van-grid-item
      >
    </van-grid>
    <!-- 推荐频道区域 -->
    <van-cell :border="false">
      <div slot="title" class="title-text">频道推荐</div>
    </van-cell>
    <van-grid :gutter="10" class="recommend-grid">
      <van-grid-item
        icon="plus"
        class="grid-item"
        v-for="(channel, index) in recommendChannels"
        :key="index"
        :text="channel.name"
        @click="onAddChannel(channel)"
      />
    </van-grid>
  </div>
</template>

<script>
import {
  getAllchannels,
  addUserChannel,
  removeUserChannel,
} from '@/api/channels'
import { mapState } from 'vuex'
import { setItem } from '@/utils/storage'
export default {
  name: 'ChannelEdit',
  components: {},
  props: {
    myChannels: {
      type: Array,
      required: true,
    },
    active: {
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      // 所有频道数据
      allChannels: [],
      // 控制编辑状态的显示
      isEdit: false,
      // 固定频道，不允许删除
      fiexdChannels: [0],
    }
  },
  computed: {
    ...mapState(['user']),
    recommendChannels() {
      const channels = []
      this.allChannels.forEach((channel) => {
        // find 遍历数组，找到不满足条件的元素项
        const ret = this.myChannels.find((myChannel) => {
          return myChannel.id === channel.id
        })
        // 如果我的 频道中不包括该频道，则收集到推荐频道中
        if (!ret) {
          channels.push(channel)
        }
      })
      // 把计算结果返回
      return channels
    },
  },
  watch: {},
  created() {
    this.loadAllchannels()
  },
  mounted() {},
  methods: {
    // 获取频道列表方法
    async loadAllchannels() {
      try {
        const { data: res } = await getAllchannels()
        this.allChannels = res.data.channels
      } catch (err) {
        this.$toast('数据获取失败')
      }
    },
    // 添加频道的方法
    async onAddChannel(channel) {
      // console.log(channel)
      this.myChannels.push(channel)
      // 数据持久化
      if (this.user) {
        try {
          await addUserChannel({
            // 频道id
            id: channel.id,
            // 序号
            seq: this.myChannels.length,
          })
        } catch (err) {
          this.$toast('保存失败，请稍后重试')
        }
      } else {
        // 未登录把数据存储到本地
        setItem('TOUTIAO_CHANNELS', this.myChannels)
      }
    },
    // 删除我的频道数据
    removeMychannel(channel, index) {
      if (this.isEdit) {
        // 如果是固定频道则不删除
        if (this.fiexdChannels.includes(channel.id)) {
          return
        }
        this.myChannels.splice(index, 1)
        // 编辑状态，执行删除频道
        if (index <= this.active) {
          this.$emit('update-cative', this.active - 1, true)
        }
        // 出来了持久化
        this.removeChannel(channel)
      } else {
        // 非编辑状态，执行切换频道
        this.$emit('update-cative', index, false)
      }
    },
    async removeChannel(channel) {
      try {
        if (this.user) {
          await removeUserChannel(channel.id)
        } else {
          // 未登录把数据存储到本地
          setItem('TOUTIAO_CHANNELS', this.myChannels)
        }
      } catch (err) {
        this.$toast('操作失败，请稍后重试')
      }
    },
  },
}
</script>

<style lang="less" scoped>
.channel-edit {
  padding: 40px 0;
  .title-text {
    font-size: 16px;
    color: #333333;
  }
  .edit-btn {
    width: 45px;
    height: 22px;
    border-radius: 10px;
  }
  /deep/ .grid-item {
    width: 60px;
    height: 40px;
    .van-grid-item__content {
      white-space: nowrap;
      background-color: #f4f5f6;
      .van-grid-item__text,
      .text {
        font-size: 12px;
        color: #222222;
        margin-top: 0;
      }
      .active {
        color: red;
      }
      .van-grid-item__icon-wrapper {
        position: unset;
      }
    }
  }
  /deep/ .my-grid {
    .grid-item {
      .van-icon-clear {
        position: absolute;
        top: -5px;
        right: -7px;
        color: #cacaca;
        font-size: 15px;
        z-index: 2;
      }
    }
  }
  /deep/ .recommend-grid {
    .grid-item {
      .van-grid-item__content {
        flex-direction: row;
        .van-icon-plus {
          font-size: 14px;
          margin-right: 2px;
        }
        .van-grid-item__text {
          margin-top: 0;
        }
      }
    }
  }
}
</style>